<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>规则管理</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }
    th, td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: left;
    }
    th {
      background-color: #f2f2f2;
    }
    .delete-btn {
      cursor: pointer;
      color: #007bff;
      border: none;
      background: none;
    }
  </style>
</head>
<body>
<h1>规则管理</h1>
<table id="rules-table">
  <thead>
  <tr>
    <th>规则 ID</th>
    <th>规则表达式</th>
    <th>操作</th>
  </tr>
  </thead>
  <tbody>
  <!-- Table rows will be dynamically added here -->
  </tbody>
</table>

<script>
  // Function to fetch rules data and populate the table
  function fetchRules() {
    $.ajax({
      url: "/api/get_rules",
      type: "GET",
      success: function(data) {
        // Clear existing table rows
        $("#rules-table tbody").empty();

        // Populate table with fetched data
        data.forEach(function(rule) {
          var row = "<tr>"
                  + "<td>" + rule.rule_id + "</td>"
                  + "<td>" + rule.rule_expression + "</td>"
                  + "<td><button class='delete-btn' data-rule-id='" + rule.rule_id + "'>删除</button></td>"
                  + "</tr>";
          $("#rules-table tbody").append(row);
        });
      },
      error: function(xhr, status, error) {
        console.error("Failed to fetch rules:", error);
      }
    });
  }

  // Initial fetch of rules on page load
  $(document).ready(function() {
    fetchRules();
  });

  // Delete button click handler
  $(document).on("click", ".delete-btn", function() {
    var ruleId = $(this).data("rule-id");

    $.ajax({
      url: "/api/delete_rule",
      type: "POST",
      data: { rule_id: ruleId },
      success: function(response) {
        console.log("Rule deleted successfully");
        // Refresh table after deletion
        fetchRules();
      },
      error: function(xhr, status, error) {
        console.error("Failed to delete rule:", error);
      }
    });
  });
</script>
</body>
</html>
